package sg.gde.rpgcreator;

import com.jme3.app.Application;
import com.jme3.app.state.AppState;
import com.jme3.app.state.AppStateManager;
import com.jme3.gde.core.scene.SceneApplication;
import com.jme3.gde.core.sceneexplorer.nodes.JmeSpatial;
import com.jme3.input.InputManager;
import com.jme3.math.Vector2f;
import com.jme3.renderer.RenderManager;
import com.jme3.scene.Spatial;
import com.jme3.scene.control.Control;
import java.util.Collection;
import java.util.concurrent.Callable;
import org.openide.util.LookupEvent;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.util.Lookup;
import org.openide.util.Lookup.Result;
import org.openide.util.LookupListener;
import org.openide.windows.WindowManager;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(dtd = "-//sg.gde.rpgcreator//CharacterManager//EN",
autostore = false)
@TopComponent.Description(preferredID = "CharacterManagerTopComponent",
//iconBase="SET/PATH/TO/ICON/HERE", 
persistenceType = TopComponent.PERSISTENCE_ALWAYS)
@TopComponent.Registration(mode = "output", openAtStartup = false)
@ActionID(category = "Window", id = "sg.gde.rpgcreator.CharacterManagerTopComponent")
@ActionReference(path = "Menu/Window" /*, position = 333 */)
@TopComponent.OpenActionRegistration(displayName = "#CTL_CharacterManagerAction",
preferredID = "CharacterManagerTopComponent")
public final class CharacterManagerTopComponent extends TopComponent implements LookupListener, AppState {

    InputManager ip;
    Control ocontrol;
//    RPGCharacterControl control;
    Spatial realSpatial;

    public CharacterManagerTopComponent() {
        initComponents();
        setName(NbBundle.getMessage(CharacterManagerTopComponent.class, "CTL_CharacterManagerTopComponent"));
        setToolTipText(NbBundle.getMessage(CharacterManagerTopComponent.class, "HINT_CharacterManagerTopComponent"));
        myInitComp();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnActive = new javax.swing.JToggleButton();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jLabel1 = new javax.swing.JLabel();
        lblControlName = new javax.swing.JLabel();
        lblSpatialName = new javax.swing.JLabel();

        org.openide.awt.Mnemonics.setLocalizedText(btnActive, org.openide.util.NbBundle.getMessage(CharacterManagerTopComponent.class, "CharacterManagerTopComponent.btnActive.text")); // NOI18N
        btnActive.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnActiveActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(CharacterManagerTopComponent.class, "CharacterManagerTopComponent.jLabel1.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(lblControlName, org.openide.util.NbBundle.getMessage(CharacterManagerTopComponent.class, "CharacterManagerTopComponent.lblControlName.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(lblSpatialName, org.openide.util.NbBundle.getMessage(CharacterManagerTopComponent.class, "CharacterManagerTopComponent.lblSpatialName.text")); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 365, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(btnActive)
                            .addComponent(jLabel1))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblSpatialName)
                            .addComponent(lblControlName))))
                .addContainerGap(436, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(lblSpatialName))
                .addGap(8, 8, 8)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnActive)
                    .addComponent(lblControlName))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 24, Short.MAX_VALUE)
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        lblControlName.getAccessibleContext().setAccessibleName(org.openide.util.NbBundle.getMessage(CharacterManagerTopComponent.class, "CharacterManagerTopComponent.jLabel2.AccessibleContext.accessibleName")); // NOI18N
    }// </editor-fold>//GEN-END:initComponents

private void btnActiveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnActiveActionPerformed
// TODO add your handling code here:
    //control.setEnabled(true);
    //control.registerWithInput(ip);
}//GEN-LAST:event_btnActiveActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JToggleButton btnActive;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JLabel lblControlName;
    private javax.swing.JLabel lblSpatialName;
    // End of variables declaration//GEN-END:variables

    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    void readProperties(java.util.Properties p) {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }
    private Result<JmeSpatial> result;

//method to register the listener;
    private void registerListener() {
        TopComponent tc = WindowManager.getDefault().findTopComponent("SceneExplorerTopComponent");

        Lookup tcLookup = tc.getLookup();
        result = tcLookup.lookupResult(JmeSpatial.class);
        result.addLookupListener(this);
    }

    private void myInitComp() {
        registerListener();
        setFormEnable(false, " Spatial Name");
    }

    @Override
    public void resultChanged(LookupEvent le) {
        Collection<JmeSpatial> items = (Collection<JmeSpatial>) result.allInstances();
        for (JmeSpatial jmeSpatial : items) {
            realSpatial = jmeSpatial.getLookup().lookup(Spatial.class);

            SceneApplication.getApplication().enqueue(new Callable() {
                @Override
                public Object call() throws Exception {
                    /*
                     control = realSpatial.getControl(RPGCharacterControl.class);
                     String info = realSpatial.getName() + " " + realSpatial.getNumControls();
                     if (control != null) {
                     //control.registerWithInput(ip);
                     setFormEnable(true, info);
                     } else {
                     setFormEnable(false, info);
                     }
                     * */
                    return null;
                }
            });
        }

        if (items.isEmpty()) {

            setFormEnable(false, null);
        }
    }

    void setFormEnable(boolean state, String name) {
        if (state) {
            lblControlName.setText(" Got the control :D !");

        } else {
            lblControlName.setText(" No control selected :D !");
        }

        if (name == null) {
            lblSpatialName.setText(" Spatial Name");
        } else {
            lblSpatialName.setText(name);
        }
        lblControlName.setEnabled(state);
        //lblSpatialName.setEnabled(state);
        btnActive.setEnabled(state);

    }

    @Override
    public void initialize(AppStateManager asm, Application aplctn) {
        ip = SceneApplication.getApplication().getInputManager();
    }

    @Override
    public boolean isInitialized() {
        return (ip != null);
    }

    @Override
    public void stateAttached(AppStateManager asm) {
    }

    @Override
    public void stateDetached(AppStateManager asm) {
    }
    Vector2f cursorPos;

    @Override
    public void update(float f) {
        cursorPos = ip.getCursorPosition();

        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                lblControlName.setText("Cursor pos :" + cursorPos.x + " " + cursorPos.y);
            }
        });
    }

    @Override
    public void render(RenderManager rm) {
    }

    @Override
    public void postRender() {
    }

    @Override
    public void cleanup() {
    }
}
